﻿using System.Data;
using System.Transactions;
using HttpServer.Models;
using Microsoft.AspNetCore.Mvc;
using MySql.Data.MySqlClient;
using Mysqlx.Crud;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace HttpServer
{
    public class SqlLinkManager
    {
         public static string sqlConnectionCommand = "server=127.0.0.1;port=3306;user=root;password=123456;database=fitu";
        //public static string sqlConnectionCommand = "server=192.168.31.106;port=3306;user=root_0;password=123456;database=fitu";//alen

        public static string GetInsertCommand(string tableName, params KeyValuePack[] keyValuePacks)
        {
            string content = "";
            string keyContent = "";
            string valueContent = "";
            for (int i = 0; i < keyValuePacks.Length; i++)
            {
                keyContent += keyValuePacks[i].key + (i >= keyValuePacks.Length - 1 ? "" : ",");
                Type type = keyValuePacks[i].GetType();
                switch (type.ToString())
                {
                    case "HttpServer.KeyIntValuePack":
                        valueContent += ((KeyIntValuePack)keyValuePacks[i]).value + (i >= keyValuePacks.Length - 1 ? "" : ",");
                        break;
                    case "HttpServer.KeyStringValuePack":
                        valueContent += $"\"{((KeyStringValuePack)keyValuePacks[i]).value}\"{(i >= keyValuePacks.Length - 1 ? "" : ",")}";
                        break;
                }

            }
            content = $"insert into {tableName}({keyContent}) values({valueContent});";
            return content;
        }
        public static string GetSearchCommand(string tableName)
        {
            string content = $"select * from {tableName}";
            return content;
        }
        public static string GetSearchCommand<T>(string tableName, string key, T value)
        {
            string content = $" select * from {tableName} where {key}={value}";
            return content;
        }
        public static T GetData<T>(string table, string key, string value)
        {
            using (MySqlConnection connection = new MySqlConnection(sqlConnectionCommand))
            {
                try
                {
                    connection.Open();
                    string checkQuery = $"SELECT * FROM {table} WHERE {key} = \"{value}\"";
                    using (var command = new MySqlCommand(checkQuery, connection))
                    {
                        using (MySqlDataReader reader = command.ExecuteReader())
                        {
                            if (!reader.HasRows)
                            {
                                return default;
                            }
                        }
                        using (MySqlDataAdapter adapter = new MySqlDataAdapter(command))
                        {
                            DataTable dataTable = new DataTable();
                            adapter.Fill(dataTable);
                            string jsonResult = JsonConvert.SerializeObject(dataTable);
                            jsonResult= jsonResult.Replace('[', ' ');
                            jsonResult=jsonResult.Replace(']', ' ');
                            var settings = new JsonSerializerSettings
                            {
                                ContractResolver = new DefaultContractResolver
                                {
                                    NamingStrategy = new CamelCaseNamingStrategy() // 如果你想要的是camelCase命名风格
                                }
                            };
                            T result = JsonConvert.DeserializeObject<T>(jsonResult, settings);
                            return result;
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
            return default;
        }
        public static string GetData(string table,string key,string value)
        {
            using (MySqlConnection connection = new MySqlConnection(sqlConnectionCommand))
            {
                try
                {
                    connection.Open();
                    string checkQuery = $"SELECT * FROM {table} WHERE {key} = \"{value}\"";
                    using (var command = new MySqlCommand(checkQuery, connection))
                    {
                        using (MySqlDataReader reader = command.ExecuteReader())
                        {
                            if (!reader.HasRows)
                            {
                                return null;
                            }
                        }
                        using (MySqlDataAdapter adapter = new MySqlDataAdapter(command))
                        {
                            DataTable dataTable = new DataTable();
                            adapter.Fill(dataTable);
                            string jsonResult = JsonConvert.SerializeObject(dataTable);
                            return jsonResult;
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
            return null;
        }
        public static int InsertData(string table, params KeyValuePack[] keyValuePacks)
        {
            using (MySqlConnection connection = new MySqlConnection(sqlConnectionCommand))
            {
                connection.Open();
                try
                {
                    int index = -1;
                    using (MySqlCommand command = new MySqlCommand(GetInsertCommand(table, keyValuePacks) + "select LAST_INSERT_ID();", connection))
                    {
                        index = Convert.ToInt32(command.ExecuteScalar());
                    }
                    return index;
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"发生错误: {ex.Message}");
                }
            }
            return -1;
        }
    }
    public abstract class KeyValuePack
    {
        public string key;
    }
    public class KeyIntValuePack: KeyValuePack
    {
        public int value;
        public KeyIntValuePack(string key,int value)
        {
            this.key = key;
            this.value = value;
        }
    }
    public class KeyStringValuePack: KeyValuePack
    {
        public string value;
        public KeyStringValuePack(string key, string value)
        {
            this.key = key;
            this.value = value;
        }
    }
    public class RequestData
    {
        public int code { get; set; }
        public string message { get; set; }
        public object data { get; set; }

        public RequestData(int code, string message ,object data=null)
        {
            this.code = code;
            this.message = message;
            this.data = data;
        }
    }
}
